package com.greatwqs.wmall.user.provider.service.client;

import com.greatwqs.wmall.user.client.model.UserResponse;
import com.greatwqs.wmall.user.client.service.UserClientService;
import com.greatwqs.wmall.user.provider.manager.UserLoginManager;
import com.greatwqs.wmall.user.provider.manager.UserManager;
import com.greatwqs.wmall.user.provider.mapper.UserLoginMapper;
import com.greatwqs.wmall.user.provider.model.po.User;
import com.greatwqs.wmall.user.provider.model.po.UserLogin;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Slf4j
@DubboService(version = "v1")
public class UserClientServiceImpl implements UserClientService {

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private UserManager userManager;

    @Autowired
    private UserLoginManager userLoginManager;

    @Autowired
    private UserLoginMapper userLoginMapper;

    @Override
    public UserResponse getUserByToken(String loginToken) {
        UserLogin userLogin = userLoginManager.getValidatedPoNotNull(loginToken);
        if (userLogin.needRefreshExpireTime()) {
            userLoginManager.refresh(userLogin);
        }
        User user = userManager.getPoNotNull(userLogin.getUserId());
        return modelMapper.map(user, UserResponse.class);
    }

    @Override
    public void deleteExpiredTokens() {
        log.info("UserClientServiceImpl deleteExpiredTokens running");
        List<UserLogin> expiredList = userLoginMapper.selectListExpired(100);
        while (CollectionUtils.isNotEmpty(expiredList)) {
            for (UserLogin expire : expiredList) {
                userLoginManager.delete(expire);
                log.debug("UserClientServiceImpl delete expired token: " + expire.getLoginToken());
            }

            expiredList = userLoginMapper.selectListExpired(100);
        }
    }
}
